package com.banciyuan.bcywebview.biz.exhibition;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.PartyApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.Exhibition;

/**
 * Created by squall on 2016/8/31.
 */
public class ExhibitionFragment extends BaseLazyContainerFragment implements View.OnClickListener {

    private static final int GO_LOCATION = 1024;

    private ListView mListView;
    private PullToRefreshListView mRefreash;
    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private TextView month;
    private TextView pre;
    private TextView next;
    private TextView empty;
    private LinearLayout city;
    private TextView city_name;

    private RequestQueue queue;

    private String city_id = "0";
    private int index;
    private int page = 1;
    private long start_time;
    private long end_time;
    private long now;
    private boolean is_load;
    private boolean is_end;


    private List<Exhibition> elist = new ArrayList<>();
    private ExhibitionAdapter exhibitionAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View viewRoot=inflater.inflate(R.layout.not_login_discover,null);
        initArgs();
        initProgressbar(viewRoot);
        initUi(viewRoot);
        initAction();
        return viewRoot;
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initArgs() {
        getMonth(getCalender());
        queue = VolleyQueue.getRquest(getActivity());
    }

    @Override
    protected void initUi(View rootView) {
        mRefreash = (PullToRefreshListView) rootView.findViewById(R.id.refreshview);
        mListView = mRefreash.getRefreshableView();

        View header=View.inflate(getActivity(),R.layout.exhibition_item_header,null);
        month = (TextView) header.findViewById(R.id.time_now);
        pre = (TextView) header.findViewById(R.id.month_pre);
        next = (TextView) header.findViewById(R.id.month_next);
        empty = (TextView) header.findViewById(R.id.no_party);
        city = (LinearLayout) header.findViewById(R.id.switch_city);
        city_name = (TextView) header.findViewById(R.id.switch_city_name);
        mListView.addHeaderView(header);

        month.setText(getMonth(getCalender()));
    }

    @Override
    protected void initAction() {
        next.setOnClickListener(this);
        pre.setOnClickListener(this);
        city.setOnClickListener(this);
        mRefreash.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!is_load && !is_end) {
                    page++;
                    getParty();
                }
            }
        });

        mRefreash.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                is_load = false;
                is_end = false;
                page = 1;
                getParty();
            }
        });
    }

    private String getMonth(Calendar calendar) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM");
        now = calendar.getTimeInMillis();
        return simpleDateFormat.format(calendar.getTime());
    }

    @Override
    protected void initProgressbar(View rootView) {
        mProgressbarView = rootView.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                getParty();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initData() {
        getTime();
        getParty();
    }

    private void getTime() {
        String url = HttpUtils.BASE_URL + PartyApi.getPartyTime();
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONObject result = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        JSONObject start = result.getJSONObject("start_time");
                        JSONObject end = result.getJSONObject("end_time");
                        start_time = Long.parseLong(start.getString("filter"));
                        end_time = Long.parseLong(end.getString("filter"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        };
        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), null);
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, null, onSucc, onErrorProxy);
        queue.add(stringRequestParam);
    }

    private void getParty() {
        is_load = true;
        String url = HttpUtils.BASE_URL + PartyApi.getmonthParty();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair("month_date", String.valueOf(now / 1000)));
        pairs.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(page)));
        pairs.add(new BcyPair("city_id", String.valueOf(city_id)));
        Map map = HttpUtils.getData(pairs);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                        JSONObject jsonObject = new JSONObject(response);
                        Gson gson = new Gson();
                        List<Exhibition> templist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<Exhibition>>() {
                        }.getType());
                        renderData(templist);
                    } else {
                        is_load = false;
                        mProgressbarHelper.onFailed();
                        mRefreash.onRefreshComplete();
                    }
                } catch (Exception e) {
                    is_load = false;
                    mProgressbarHelper.onFailed();
                    mRefreash.onRefreshComplete();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                is_load = false;
                mProgressbarHelper.onFailed();
                mRefreash.onRefreshComplete();
            }
        };
        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(stringRequestParam);
    }

    private void renderData(List<Exhibition> templist) {
        if (templist.size() == 0) {
            if (page == 1) {
                empty.setVisibility(View.VISIBLE);
            }
            is_end = true;
        } else {
            empty.setVisibility(View.GONE);
        }
        if (page == 1) {
            elist.clear();
        }
        elist.addAll(templist);
        if (exhibitionAdapter == null) {
            exhibitionAdapter = new ExhibitionAdapter(elist, getActivity());
            mListView.setAdapter(exhibitionAdapter);
        } else {
            exhibitionAdapter.notifyDataSetChanged();
        }
        is_load = false;
        mRefreash.onRefreshComplete();
        mProgressbarHelper.onSuccess();
    }

    @Override
    public void onClick(View v) {
        Calendar calendar = getCalender();
        switch (v.getId()) {
            case R.id.month_next:
                calendar.add(Calendar.MONTH, ++index);
                if (calendar.getTimeInMillis() / 1000 > end_time) {
                    index--;
                    break;
                }
                month.setText(getMonth(calendar));
                mRefreash.setRefreshing();
                break;
            case R.id.month_pre:
                calendar.add(Calendar.MONTH, --index);
                if (calendar.getTimeInMillis() / 1000 < start_time) {
                    index++;
                    break;
                }
                month.setText(getMonth(calendar));
                mRefreash.setRefreshing();
                break;
            case R.id.switch_city:
                Intent intent = new Intent(getActivity(), ExhibitionLocationActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, city_name.getText().toString());
                getActivity().startActivityForResult(intent, GO_LOCATION);
                break;
        }
    }

    private Calendar getCalender() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DATE, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (requestCode == GO_LOCATION) {
                if (data != null) {
                    String name = data.getStringExtra("city");
                    city_id = data.getStringExtra("city_id");
                    city_name.setText(name);
                    is_end = false;
                    is_load = false;
                    page = 1;
                    mRefreash.setRefreshing();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void selfUpdateData() {
        if (mRefreash != null) {
            mRefreash.setRefreshing();
        }
    }
}
